// 封装axios
import axios from 'axios'
import { Message } from 'element-ui'
// 创建实例
// axios.create(config)
const http = axios.create({
  baseURL: 'http://timemeetyou.com:8889/api/private/v1/',
  timeout: 100,
  retry: 4,
  retryDelay: 1000
})

// 拦截器请求
// 超时重请功能
http.interceptors.request.use(config => {
  const token = window.sessionStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 拦截器响应
http.interceptors.response.use(res => {
  return res
}, error => {
  console.log(error.config)
  // return Promise.reject(error)
  const config = error.config
  // 如果config和config的retry不存在,就返回promise.reject
  if (!config || !config.retry) return Promise.reject(error)
  // 重复请求的次数
  config.__retryCount = config.__retryCount || 0
  // 请求次数过多,也返回promise.reject
  if (config.__retryCount >= config.retry) return Message.error('登录超时！')
  config.__retryCount++
  const backoff = new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, config.retryDelay || 1)
  })
  return backoff.then(() => {
    return http(config)
  })
})

export default http
